package org.amos.gateway.filter;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.constant.SystemConstant;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器，为请求添加 tenantId和traceId
 */
@Slf4j
@Component
public class ForwardSystemFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String tenantNo = exchange.getRequest().getHeaders().getFirst(SystemConstant.SYS_TENANT_NO);
        String traceId = UUID.fastUUID().toString(true);
        MDC.put(SystemConstant.TRACE_ID, traceId);
        ServerHttpRequest newRequest = exchange.getRequest().mutate()
                .headers(h -> h.add(SystemConstant.SYS_TENANT_NO, tenantNo))
                .headers(h -> h.add(SystemConstant.TRACE_ID, traceId))
                .build();
        ServerWebExchange build = exchange.mutate().request(newRequest).build();
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return FilterOrder.REQUEST_SYSTEM_FILTER_ORDER;
    }
}
